class Feed < ActiveRecord::Base
  
  include DynamicDefaultScoping
  
  validates :enterprise_id, :presence => true
  validates :order_item_id,
    :presence =>true

  belongs_to :order_item
  belongs_to :installation
  belongs_to :after_service
  belongs_to :order_made
  belongs_to :enter
  belongs_to :order_made_payment

  has_many :tasks, :dependent => :destroy

  default_scope :current_enterprise,lambda {where(:enterprise_id => Enterprise.current_id )}
  
  before_validation do |feed|
    feed.position = Feed.last.try(:id) || 0 + 1
  end
  
  after_save do |feed|
    feed.reset_feeds!
  end

  after_destroy do |feed|
    feed.reset_feeds!
  end

  def position!(position)
    self.position = position
    save(:validate => false)
  end
  
  def reset_feeds!
    logger.debug "reset_feeds!============================================="
    order_item.try(:reset_feed!) 
    installation.try(:reset_feed!) 
    order_made.try(:reset_feed!) 
    enter.try(:reset_feed!)
    order_made_payment.try(:reset_feed!)
    after_service.try(:reset_feed!)
  end
end
